package org.epidroid.epidroid.androsoul.engine.contacts;

import java.util.HashMap;
import java.util.Iterator;

import org.epidroid.epidroid.androsoul.engine.AndroSoul;
import org.epidroid.epidroid.androsoul.engine.conversation.Conversation;

/**
 * @author conrath Contains the set of contacts Handle update of contacts status
 */
public class ContactDictionary {
	// Hash table that contains all the contacts
	private HashMap<String, NetsoulContact> _map;
	private AndroSoul _androsoul = null;
	private int _lastContactId = 0;

	public ContactDictionary(AndroSoul androsoul) {
		_androsoul = androsoul;
		_map = new HashMap<String, NetsoulContact>();
	}

	public void add(NetsoulContact c) {
		if (_map.containsKey(c.getName()))
			return;
		_lastContactId++;
		c.setId(_lastContactId);
		_map.put(c.getName(), c);
	}

	public NetsoulContact get(String name) {
		return _map.get(name);
	}

	public boolean has(String name) {
		return _map.containsKey(name);
	}

	public Iterator<NetsoulContact> iterator() {
		return _map.values().iterator();
	}

	/**
	 * @return list of contacts respecting the netsoul format example:
	 *         {conrat_a, margue_j}
	 */
	public String generateNetsoulList() {
		String tmp = "";
		Iterator<NetsoulContact> it = _map.values().iterator();
		while (it.hasNext()) {
			NetsoulContact c = it.next();
			tmp += c.getName();
			c.clearLocations();
			if (it.hasNext())
				tmp += ",";
		}
		return tmp;
	}

	/**
	 * Delete all locations for every contact
	 */
	public void clearLocations() {
		Iterator<NetsoulContact> it = _map.values().iterator();
		while (it.hasNext()) {
			NetsoulContact c = it.next();
			c.clearLocations();
		}
	}

	public NetsoulContact createContact(String name) {
		if (get(name) != null)
			return get(name);
		NetsoulContact c = new NetsoulContact(name);
		// create conversation
		c.setConversation(new Conversation(c, _androsoul));
		add(c);
		return c;
	}
}
